#include "ekran_ocen.h"
#include "ui_ekran_ocen.h"
#include <QJsonArray>

#include <QColor>
#include <QFont>
#include <QMessageBox>
#include <QCloseEvent>
#include <QApplication>
#include <QPalette>

QString secToMinSec(int seconds)
{
    QString m = QString::number(seconds / 60);
    QString s = QString::number(seconds % 60);
    if(m.length() == 1) m = "0" + m;
    if(s.length() == 1) s = "0" + s;
    return m + ":" + s;
}

ekran_ocen::ekran_ocen(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::ekran_ocen)
{
    ui->setupUi(this);
    this->setWindowTitle("ИСAП-экран");
    ui->listWidget->hide();
    sqlRequest = new SqlRequest();
    settings = new QSettings(ORGANIZATION_NAME, APPLICATION_NAME);

    keyCtrlF = new QShortcut(this);
    keyCtrlF->setKey(Qt::CTRL + Qt::Key_F);
    connect(keyCtrlF, SIGNAL(activated()), this, SLOT(slotShortcutCtrlF()));
    ui->katek->setWordWrap(true);
    ui->lTimer->hide();
    groupsGrades[0] = ui->first_accurasy;
    groupsGrades[1] = ui->first_presentation;
    groupsGrades[2] = ui->second_accurasy;
    groupsGrades[3] = ui->second_presentation;
    ui->listWidget->hide();
    tmr = new QTimer(this);
    tmr->setInterval(1000);
    connect(tmr, SIGNAL(timeout()), this, SLOT(updateTime()));
    tmrLine = new QTimer(this);
    tmrLine->setInterval(1000);
    connect(tmrLine, SIGNAL(timeout()), this, SLOT(runLine()));
    tmrRange = new QTimer(this);
    tmrRange->setInterval(5000);
    connect(tmrRange, SIGNAL(timeout()), this, SLOT(vivrange()));
}

ekran_ocen::~ekran_ocen()
{
    delete ui;
    delete tmr;
    delete tmrLine;
    delete tmrRange;
}

void ekran_ocen::startTimer() {
    clickBtnTimer += 1;
    if(clickBtnTimer%2 != 0) {
        ui->lTimer->show();
        secondVistup = 90;
        ui->lTimer->setText(secToMinSec(secondVistup));
        tmr->start();
    }
    if(clickBtnTimer%2 == 0) {
        clickBtnTimer = 0;
//        ui->lTimer->hide();
        tmr->stop();
    }
}

void ekran_ocen::updateTime() {
    secondVistup--;
    ui->lTimer->setText(secToMinSec(secondVistup));
    if(!secondVistup) ui->lTimer->setText(secToMinSec(secondVistup));
}

//Показываем зачёркивая оценку какой судья выставил оценку
void ekran_ocen::showJudgesOcen(QJsonObject json) {
    for(int i= 0; i<pokaz*2; i++) {
        for(int j=0; j<countJudges; j++) {
            lscore[i][j]->show();
        }
    }
    if(json["ocenkiCount"].toInt() == countJudges) totalObject = json;
}

void ekran_ocen::slotShortcutCtrlF()
{
    clickF += 1;
    if(clickF%2 != 0) QWidget::showFullScreen();
    if(clickF%2 == 0) QWidget::showMaximized();
}

//Вывод выступающего, категории, пхумсэ
void ekran_ocen::recieveDataSys(QJsonObject json, int kolPhumse) {
    QFont resetAccuracyPresentation;
    QFont ocen;
    ocen.setPixelSize(70);
    ui->total1ek->hide();
    ui->total2ek->hide();
    ui->totalek->hide();

    ui->lTimer->hide();

    ui->sportek->show();
    ui->phumek->show();
    ui->katek->show();
    ui->listWidget->hide();
    countJudges = settings->value("SETTINGS_KSUD").toInt();
    if(show == 0) {
        for (int j=0; j<4; j++) {
            for(int i = 0; i < countJudges; i++) {
                lscore[j][i] = new QLabel();
                lscore[j][i]->setAlignment(Qt::AlignCenter);
                lscore[j][i]->setProperty("styleclass", "results");
                lscore[j][i]->setFont(ocen);
                lscore[j][i]->setFixedSize(140,140);
                lscore[j][i]->setText("0.0");
                groupsGrades[j]->addWidget(lscore[j][i]);
            }
        }
    }

    kolPhum = kolPhumse;

    if(tmrInt == 1) {
        tmrRange->stop();
        tmrInt = 0;
    }
    katek = json["kategoria"].toString();
    pokaz = json["pokaz"].toInt();
    idvist = json["idvist"].toInt();
    nomerKrug = json["krugNomer"].toInt();

    for(int j=0; j<4; j++) {
        for(int i = 0; i < countJudges; i++) {
            if(pokaz == 1) {
                lscore[j][i]->setText("0.0");
                resetAccuracyPresentation = lscore[j][i]->font();
                resetAccuracyPresentation.setStrikeOut(false);
                lscore[j][i]->setFont(resetAccuracyPresentation);
                countVistup = pokaz-1;
            } else countVistup = pokaz;
            lscore[j][i]->hide();
        }
    }

    ui->sportek->setText(json["sportsmen"].toString());
    ui->phumek->setText(QString::number(pokaz) + " : " + json["phumse"].toString());
    ui->katek->setText(katek);

    QFontMetrics fm(ui->sportek->font());
    int pixelsWide = fm.horizontalAdvance(ui->sportek->text());
    tmrLine->stop();
    if(QApplication::screens().size() > 1) {
        QScreen* screen = QApplication::screens().at(1);
        QSize size = screen->availableSize();
        wEkran = size.width()-50;
        ui->sportek->setFixedWidth(wEkran);
        if (pixelsWide > wEkran) {
            tmrLine->start();
        }
    }
}

void ekran_ocen::runLine() {
    const int length = ui->sportek->text().length();

    if(++m_shift >= length)
      m_shift = 0;

    ui->sportek->setText(ui->sportek->text().right(m_shift) + ui->sportek->text().left(length - m_shift));
}

void ekran_ocen::minusPerfomance() {
    tempCalc -= 3;
}

//Получение итоговых баллов
void ekran_ocen::recieveOcenSys(QJsonObject totalObj) {
    QFont accuracyStrikeMin;
    QFont presentationStrikeMin;
    QFont accuracyStrikeMax;
    QFont presentationStrikeMax;
    QJsonObject mestoObject;
    QJsonArray ja;
    QJsonObject subtree;
    QJsonValue jv;
    int total, accuracyMin, accuracyMax, presentationMin, presentationMax;
    QMap<QString, int> minAccuracy, maxAccuracy, minPresentation, maxPresentation;
    tempCalc = totalObj["tempCalc"].toInt();
    show = 1;

    accuracyMin = totalObj["accuracyMin"].toInt();
    accuracyMax = totalObj["accuracyMax"].toInt();
    presentationMin = totalObj["presentationMin"].toInt();
    presentationMax = totalObj["presentationMax"].toInt();
    total = totalObj["total"].toInt();
    jv = totalObject.value("ocenki");
    if(jv.isArray()) {
        ja = jv.toArray();
        for (int i=0; i<ja.count(); i++) {
            subtree = ja.at(i).toObject();
            if(accuracyMin == subtree["ocenki_t"].toInt()) minAccuracy["nomersud"] = subtree["ocenki_nomsud"].toInt()-1;
            if(accuracyMax == subtree["ocenki_t"].toInt()) maxAccuracy["nomersud"] = subtree["ocenki_nomsud"].toInt()-1;
            if(presentationMin == subtree["ocenki_p"].toInt()) minPresentation["nomersud"] = subtree["ocenki_nomsud"].toInt()-1;
            if(presentationMax == subtree["ocenki_p"].toInt()) maxPresentation["nomersud"] = subtree["ocenki_nomsud"].toInt()-1;
            lscore[countVistup][subtree["ocenki_nomsud"].toInt()-1]->setText(QString::number(subtree["ocenki_t"].toDouble()/10, 'f', 1));
            lscore[countVistup+1][subtree["ocenki_nomsud"].toInt()-1]->setText(QString::number(subtree["ocenki_p"].toDouble()/10, 'f', 1));
        }
    }

    if(countJudges > 3) {
        accuracyStrikeMin = lscore[countVistup][minAccuracy["nomersud"]]->font();
        presentationStrikeMin = lscore[countVistup+1][minPresentation["nomersud"]]->font();
        accuracyStrikeMax = lscore[countVistup][maxAccuracy["nomersud"]]->font();
        presentationStrikeMax = lscore[countVistup+1][maxPresentation["nomersud"]]->font();
        accuracyStrikeMin.setStrikeOut(true);
        presentationStrikeMin.setStrikeOut(true);
        accuracyStrikeMax.setStrikeOut(true);
        presentationStrikeMax.setStrikeOut(true);
        lscore[countVistup][minAccuracy["nomersud"]]->setFont(accuracyStrikeMin);
        lscore[countVistup][maxAccuracy["nomersud"]]->setFont(accuracyStrikeMax);
        lscore[countVistup+1][minPresentation["nomersud"]]->setFont(presentationStrikeMin);
        lscore[countVistup+1][maxPresentation["nomersud"]]->setFont(presentationStrikeMax);
    }

    switch(pokaz) {
    case 1:
        ui->total1ek->show();
        ui->total1ek->setText(QString::number(double(tempCalc)/100, 'f', 2));
        break;
    case 2:
        ui->total1ek->show();
        ui->total2ek->show();
        ui->totalek->show();
        total = 10 * total / 2;
        if(total % 10 == 5)
        {
            total /= 10;
            total += total % 2;
        }
        else
            total = qRound(total / 10.0);
        ui->total2ek->setText(QString::number(double(tempCalc)/100, 'f', 2));
        ui->totalek->setText(QString::number(double(total)/100, 'f', 2));
        break;
    }

    if(kolPhum == pokaz) {
        mestoObject = sqlRequest->selectMesto(katek, nomerKrug);
        for (int j=0; j<mestoObject.count(); j++) {
            jv = mestoObject.value("mesto"+QString::number(j+1));
            if(jv.isArray()) {
                ja = jv.toArray();
                subtree = ja.at(0).toObject();
                if(subtree["idvistuplenie"].toInt() == idvist) {
                    ui->totalek->setText(QString::number(double(total)/100, 'f', 2) + "\n\n" + "Место \n " + QString::number(subtree["mesto"].toInt()));
                }
            }
        }
    }
}

//Вывод спортсменов по рангу
void ekran_ocen::range() {
    QJsonValue jv;
    QJsonArray ja;
    ui->phumek->hide();
    ui->total1ek->hide();
    ui->total2ek->hide();
    ui->totalek->hide();
    ui->sportek->hide();
    for(int j=0; j<4; j++) {
        for(int i = 0; i < countJudges; i++) {
            lscore[j][i]->hide();
        }
    }
    rangeObject = sqlRequest->selectRange(katek,nomerKrug);
    ui->listWidget->show();
    rangeViv = 0;
    jv = rangeObject.value("rang");
    if(jv.isArray()) {
        ja = jv.toArray();
        if(ja.count() < 10) {
            rangeCount = ja.count();
        }
        if(ja.count() > 10 && tmrInt == 0) {
            ui->listWidget->setRowCount(10);
            rangeCount = 10;
            tmrRange->start();
            tmrInt = 1;
        }
    }
    vivrange();
}

void ekran_ocen::vivrange() {
    QFont total;
    total.setPixelSize(70);
    QJsonValue jv;
    QJsonArray ja;
    QJsonObject subtree;
    QTableWidgetItem *item[5];
    ui->listWidget->clear();
    ui->listWidget->setRowCount(rangeCount);
    ui->listWidget->setColumnCount(5);
    ui->listWidget->horizontalHeader()->setStretchLastSection(true);
    jv = rangeObject.value("rang");
    if(jv.isArray()) {
        ja = jv.toArray();
        for (int j=0; j<rangeCount; j++) {
            rangeViv += 1;
            subtree = ja.at(j).toObject();
            for(int i=0; i<5; i++) {
                item[i] = new QTableWidgetItem();
                switch (i) {
                case 0:
                    item[i]->setText(QString::number(rangeViv));
                    break;
                case 1:
                    item[i]->setText(subtree["rang_athlethe"].toString());
                    break;
                case 2:
                    item[i]->setText(subtree["rang_sumpres"].toString());
                    break;
                case 3:
                    item[i]->setText(subtree["rang_sumobsh"].toString());
                    break;
                case 4:
                    item[i]->setText(subtree["rang_tot"].toString());
                    break;
                }
                item[i]->setTextAlignment(Qt::AlignCenter);
                item[i]->setFont(total);
                ui->listWidget->setItem(j, i, item[i]);
            }
            ui->listWidget->setRowHeight(j, 80);
        }
    }

    ui->listWidget->setColumnWidth(0, wEkran/6);
    ui->listWidget->setColumnWidth(1, wEkran/2);
    ui->listWidget->setColumnWidth(2, wEkran/6);
    ui->listWidget->setColumnWidth(3, wEkran/6);
    ui->listWidget->setColumnWidth(4, wEkran/6);
    ui->listWidget->setShowGrid(true);
    if(rangeViv > rangeCount) {
        rangeViv = 0;
    }
}

